package com.mangowang.module.main.ui;


import android.media.Image;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bigkoo.convenientbanner.ConvenientBanner;
import com.bigkoo.convenientbanner.holder.CBViewHolderCreator;
import com.google.protobuf.InvalidProtocolBufferException;
import com.mangowang.lib.common.base.BaseFragment;
import com.mangowang.lib.common.help.GlideHelper;
import com.mangowang.lib.common.net.Apis;
import com.mangowang.lib.common.net.NetworkManager;
import com.mangowang.lib.common.net.WebApis;
import com.mangowang.lib.common.net.interfaces.OnRequestCallBack;
import com.mangowang.lib.common.proto.Change;
import com.mangowang.lib.common.proto.Index;
import com.mangowang.lib.common.proto.MemberOuterClass;
import com.mangowang.module.main.dialog.ShowBannerDialog;
import com.mangowang.module.main.holder.BannerImageHoderView;
import com.mangowang.module.main.web.ui.WebViewActivity;
import com.mangowang.module.main.R;
import com.mangowang.module.main.R2;
import com.mangowang.module.main.bean.BottomBean;
import com.mangowang.module.main.holder.BannerChangeHolderView;
import com.ruffian.library.widget.RLinearLayout;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;
import kale.ui.view.dialog.EasyDialog;


/**
 * Created by Administrator on 2018/2/2 0002.
 */

public class HomeFragment extends BaseFragment implements View.OnClickListener {


    Unbinder unbinder; // bufferKnife绑定

    // 广告轮播
    @BindView(R2.id.home_convenient_banner)
    ConvenientBanner convenientBanner;

    // 底部轮播
    @BindView(R2.id.home_button_banner)
    ConvenientBanner buttonBanner;


    @BindView(R2.id.image_1)
    ImageView image_1;
    @BindView(R2.id.image_2)
    ImageView image_2;
    @BindView(R2.id.image_3)
    ImageView image_3;
    @BindView(R2.id.image_4)
    ImageView image_4;
    @BindView(R2.id.image_5)
    ImageView image_5;
    @BindView(R2.id.image_6)
    ImageView image_6;
    @BindView(R2.id.image_7)
    ImageView image_7;
    @BindView(R2.id.image_8)
    ImageView image_8;
    @BindView(R2.id.image_9)
    ImageView image_9;
    @BindView(R2.id.image_10)
    ImageView image_10;


    @BindView(R2.id.text_1)
    TextView text_1;
    @BindView(R2.id.text_2)
    TextView text_2;
    @BindView(R2.id.text_3)
    TextView text_3;
    @BindView(R2.id.text_4)
    TextView text_4;
    @BindView(R2.id.text_5)
    TextView text_5;
    @BindView(R2.id.text_6)
    TextView text_6;
    @BindView(R2.id.text_7)
    TextView text_7;
    @BindView(R2.id.text_8)
    TextView text_8;
    @BindView(R2.id.text_9)
    TextView text_9;
    @BindView(R2.id.text_10)
    TextView text_10;

    @BindView(R2.id.home_category_1)
    LinearLayout home_category_1;
    @BindView(R2.id.home_category_2)
    LinearLayout home_category_2;
    @BindView(R2.id.home_category_3)
    LinearLayout home_category_3;
    @BindView(R2.id.home_category_4)
    LinearLayout home_category_4;
    @BindView(R2.id.home_category_5)
    LinearLayout home_category_5;
    @BindView(R2.id.home_category_6)
    LinearLayout home_category_6;
    @BindView(R2.id.home_category_7)
    LinearLayout home_category_7;
    @BindView(R2.id.home_category_8)
    LinearLayout home_category_8;
    @BindView(R2.id.home_category_9)
    LinearLayout home_category_9;
    @BindView(R2.id.home_category_10)
    LinearLayout home_category_10;

    @BindView(R2.id.iv_message)
    ImageView iv_message;

    @BindView(R2.id.tv_marquess)
    TextView tvMarquess;

    @BindView(R2.id.ll_category_two)
    LinearLayout ll_category_two;


    @BindView(R2.id.iv_app_logo)
    ImageView iv_app_logo;


    @BindView(R2.id.ll_message)
    RLinearLayout ll_message;


    @BindView(R2.id.loop_one)
    ImageView loop_one;

    @BindView(R2.id.loop_two)
    ImageView loop_two;

    @BindView(R2.id.loop_three)
    ImageView loop_three;

    private List<TextView> cateTextViewS = new ArrayList<>();
    private List<ImageView> cateImageViewS = new ArrayList<>();
    private List<LinearLayout> cateLineViewS = new ArrayList<>();
    private List<Index.get_show_list.List> advDatas = new ArrayList<>(); // TOPbanner
    private List<Change.month_datas> bottomData = new ArrayList<>(); // bottomBanner


    private List<MemberOuterClass.Appbtn> appbtnListList = new ArrayList<>();

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View rootView = super.onCreateView(inflater, container, savedInstanceState);
        unbinder = ButterKnife.bind(this, rootView);
        return rootView;
    }

    @Override
    protected int getLayoutId() {
        return R.layout.home_fragment_layout;
    }


    @Override
    protected void initView() {
//        tvAppName.setText(R.string.app_name);
        initHomeButton();
        initListener();
        initTopBanner();
        initDialogBanner();
//        initBottomBanner();
        setMarqueeText();
        loadHomeButton();

    }

    private void loadHomeButton() {
        NetworkManager.INSTANCE.post(Apis.get_home_btn, new OnRequestCallBack() {
            @Override
            public void onOk(byte[] bytes) throws InvalidProtocolBufferException {
                MemberOuterClass.get_home_btn data = MemberOuterClass.get_home_btn.parseFrom(bytes);

                GlideHelper.INSTANCE.loadImage(mContext, iv_app_logo, data.getLogo());


                // 重置图标
                if (data.getAppbtnListList().size() <= appbtnListList.size()) {
                    for (int i = 0; i <= appbtnListList.size(); i++) {
                        cateTextViewS.get(i).setText("");
                        cateImageViewS.get(i).setImageResource(R.color.transparent);
                        cateLineViewS.get(i).setOnClickListener(null);
                    }
                }
                // 设置值
                appbtnListList = data.getAppbtnListList();
                if (appbtnListList.size() == 0) {

                } else if (appbtnListList.size() <= 4) {
                    ll_category_two.setVisibility(View.GONE);
                    for (int i = 0; i < appbtnListList.size(); i++) {
                        GlideHelper.INSTANCE.loadImage(mContext, cateImageViewS.get(i), appbtnListList.get(i).getImg());
                        cateTextViewS.get(i).setText(appbtnListList.get(i).getName());
                        cateLineViewS.get(i).setOnClickListener(HomeFragment.this);
                    }
                } else {
                    ll_category_two.setVisibility(View.VISIBLE);
                    for (int i = 0; i < appbtnListList.size(); i++) {
                        GlideHelper.INSTANCE.loadImage(mContext, cateImageViewS.get(i), appbtnListList.get(i).getImg());
                        cateTextViewS.get(i).setText(appbtnListList.get(i).getName());
                        cateLineViewS.get(i).setOnClickListener(HomeFragment.this);
                    }
                }
            }

            @Override
            public void onError(int errorCode, String errorMessage) {
                // 重置图标
                for (int i = 0; i <= appbtnListList.size(); i++) {
                    cateTextViewS.get(i).setText("");
                    cateImageViewS.get(i).setImageResource(R.color.transparent);
                    cateLineViewS.get(i).setOnClickListener(null);
                }
            }
        });
    }

    private void initHomeButton() {

        home_category_1.setTag("1");
        home_category_2.setTag("2");
        home_category_3.setTag("3");
        home_category_4.setTag("4");
        home_category_5.setTag("5");
        home_category_6.setTag("6");
        home_category_7.setTag("7");
        home_category_8.setTag("8");
        home_category_9.setTag("9");
        home_category_10.setTag("10");


        cateLineViewS.add(home_category_1);
        cateLineViewS.add(home_category_2);
        cateLineViewS.add(home_category_3);
        cateLineViewS.add(home_category_4);
        cateLineViewS.add(home_category_5);
        cateLineViewS.add(home_category_6);
        cateLineViewS.add(home_category_7);
        cateLineViewS.add(home_category_8);
        cateLineViewS.add(home_category_9);
        cateLineViewS.add(home_category_10);

        cateTextViewS.add(text_1);
        cateTextViewS.add(text_2);
        cateTextViewS.add(text_3);
        cateTextViewS.add(text_4);
        cateTextViewS.add(text_5);
        cateTextViewS.add(text_6);
        cateTextViewS.add(text_7);
        cateTextViewS.add(text_8);
        cateTextViewS.add(text_9);
        cateTextViewS.add(text_10);

        cateImageViewS.add(image_1);
        cateImageViewS.add(image_2);
        cateImageViewS.add(image_3);
        cateImageViewS.add(image_4);
        cateImageViewS.add(image_5);
        cateImageViewS.add(image_6);
        cateImageViewS.add(image_7);
        cateImageViewS.add(image_8);
        cateImageViewS.add(image_9);
        cateImageViewS.add(image_10);
    }

    private void initListener() {

        iv_message.setOnClickListener(v -> startActivity(MessageActivity.class));
        ll_message.setOnClickListener(v -> startActivity(MessageActivity.class));
    }

    @Override
    protected void init() {

    }


    private void setMarqueeText() {
        tvMarquess.setEllipsize(TextUtils.TruncateAt.MARQUEE);
        tvMarquess.setSingleLine(true);
        tvMarquess.setSelected(true);
        tvMarquess.setFocusable(true);
        tvMarquess.setFocusableInTouchMode(true);
        NetworkManager.INSTANCE.post(Apis.system_log, new OnRequestCallBack() {
            @Override
            public void onOk(byte[] response) throws InvalidProtocolBufferException {
                MemberOuterClass.System_log data = MemberOuterClass.System_log.parseFrom(response);
                List<MemberOuterClass.System_log.System_log_list> lists = data.getSystemLogListList();
                if (lists.size() > 0)
                    tvMarquess.setText(lists.get(0).getPushTitle() + " " + lists.get(0).getPushMessage());
            }

            @Override
            public void onError(int errorCode, String errorMessage) {
                tvMarquess.setText("暂无通知");
            }
        });


    }

    /**
     * 加载数据项
     */
    private void initTopBanner() {
        // 加载banner的数据
        NetworkManager.INSTANCE.post(Apis.get_banner, new OnRequestCallBack() {
            @Override
            public void onOk(byte[] bytes) throws InvalidProtocolBufferException {
                Index.get_show_list data = Index.get_show_list.parseFrom(bytes);
                advDatas = data.getAdvListList();
                loadTopBanner(advDatas);
            }

            @Override
            public void onError(int errorCode, String errorMessage) {
//                showToast(errorMessage);
            }
        });


        NetworkManager.INSTANCE.post(Apis.get_top_list, new OnRequestCallBack() {
            @Override
            public void onOk(byte[] bytes) throws InvalidProtocolBufferException {
                Index.get_show_list data = Index.get_show_list.parseFrom(bytes);
                Log.e("get_top_list", data.toString());
                if (data.getAdvListList().size() >= 1) {
                    GlideHelper.INSTANCE.loadImage(mContext, loop_one, data.getAdvList(0).getAdvCode());
                    loop_one.setOnClickListener(v -> {
                        if (!TextUtils.isEmpty(data.getAdvList(0).getAdvId())) {  //  关联类型：0无跳转，1链接跳转，2视频详情页跳转
                            if (data.getAdvList(0).getAdvId().startsWith("http")) {
                                WebViewActivity.startActivity(mContext, data.getAdvList(0).getAdvId());
                            } else {
                                WebViewActivity.startActivity(mContext, data.getAdvList(0).getAdvId(), true);
                            }

                        }
                    });
                }
                if (data.getAdvListList().size() >= 2) {
                    GlideHelper.INSTANCE.loadImage(mContext, loop_two, data.getAdvList(1).getAdvCode());
                    loop_two.setOnClickListener(v -> {
                        if (!TextUtils.isEmpty(data.getAdvList(0).getAdvId())) {  //  关联类型：0无跳转，1链接跳转，2视频详情页跳转
                            if (data.getAdvList(0).getAdvId().startsWith("http")) {
                                WebViewActivity.startActivity(mContext, data.getAdvList(1).getAdvId());
                            } else {
                                WebViewActivity.startActivity(mContext, data.getAdvList(1).getAdvId(), true);
                            }

                        }
                    });
                }
                if (data.getAdvListList().size() >= 3) {
                    GlideHelper.INSTANCE.loadImage(mContext, loop_three, data.getAdvList(2).getAdvCode());
                    loop_three.setOnClickListener(v -> {
                        if (!TextUtils.isEmpty(data.getAdvList(2).getAdvId())) {  //  关联类型：0无跳转，1链接跳转，2视频详情页跳转
                            if (data.getAdvList(2).getAdvId().startsWith("http")) {
                                WebViewActivity.startActivity(mContext, data.getAdvList(2).getAdvId());
                            } else {
                                WebViewActivity.startActivity(mContext, data.getAdvList(2).getAdvId(), true);
                            }

                        }
                    });
                }


            }

            @Override
            public void onError(int errorCode, String errorMessage) {
//                showToast(errorMessage);
            }
        });


    }

    private void initDialogBanner() {
        // 加载banner的数据
        NetworkManager.INSTANCE.post(Apis.get_popup, new OnRequestCallBack() {
            @Override
            public void onOk(byte[] bytes) throws InvalidProtocolBufferException {
                Index.get_show_list data = Index.get_show_list.parseFrom(bytes);
                ShowBannerDialog.Builder builder = new ShowBannerDialog.Builder(mContext);
                builder.setData(data.getAdvListList());
                EasyDialog build2 = builder.build();
                build2.setCancelable(true);
                build2.show(getFragmentManager());
            }

            @Override
            public void onError(int errorCode, String errorMessage) {
//                showToast(errorMessage);
            }
        });


    }


    private void loadTopBanner(List<Index.get_show_list.List> data) {

        convenientBanner.setPages(new CBViewHolderCreator() {
            @Override
            public BannerImageHoderView createHolder(View itemView) {
                return new BannerImageHoderView(mContext, itemView);
            }

            @Override
            public int getLayoutId() {
                return R.layout.banner_top_change;
            }
        }, data);
        convenientBanner.setPageIndicator(new int[]{R.mipmap.indicator_un_selected, R.mipmap.indicator_selected})
                //设置指示器的方向
                .setPageIndicatorAlign(ConvenientBanner.PageIndicatorAlign.CENTER_HORIZONTAL);
        convenientBanner.startTurning(6000);

    }


    /**
     * 加载数据项n
     */
    private void initBottomBanner() {

        bottomData.clear();
        NetworkManager.INSTANCE.post(Apis.get_month_data, new OnRequestCallBack() {
            @Override
            public void onOk(byte[] bytes) throws InvalidProtocolBufferException {
                Change.get_month_data data = Change.get_month_data.parseFrom(bytes);
                List<Change.month_datas> list = data.getListList();
                BottomBean bottomBean = new BottomBean();
                bottomBean.setPosition(0);
                BottomBean bottomBean1 = new BottomBean();
                bottomBean1.setPosition(1);
                bottomData.addAll(list);
                loadButtonBanner(list);


            }

            @Override
            public void onError(int errorCode, String errorMessage) {
//                showToast(errorMessage);
            }
        });
    }


    private void loadButtonBanner(List<Change.month_datas> data) {
        buttonBanner.setPages(new CBViewHolderCreator() {
            @Override
            public BannerChangeHolderView createHolder(View itemView) {
                return new BannerChangeHolderView(itemView, mContext);
            }

            @Override
            public int getLayoutId() {
                return R.layout.banner_bottom_change;
            }
        }, data);

    }


    @Override
    public void onClick(View v) {


        switch (v.getTag().toString()) {
            case "1":
                if (appbtnListList.get(0).getJump().equals("client")) {
                    GoInto(appbtnListList.get(0).getValue());
                } else {
                    WebViewActivity.startActivity(mContext, WebApis.serverHead + appbtnListList.get(0).getH5Url());
                }
                break;
            case "2":
                if (appbtnListList.get(1).getJump().equals("client")) {
                    GoInto(appbtnListList.get(1).getValue());
                } else {
                    WebViewActivity.startActivity(mContext, WebApis.serverHead + appbtnListList.get(1).getH5Url());
                }
                break;
            case "3":
                if (appbtnListList.get(2).getJump().equals("client")) {
                    GoInto(appbtnListList.get(2).getValue());
                } else {
                    WebViewActivity.startActivity(mContext, WebApis.serverHead + appbtnListList.get(2).getH5Url());
                }
                break;
            case "4":
                if (appbtnListList.get(3).getJump().equals("client")) {
                    GoInto(appbtnListList.get(3).getValue());
                } else {
                    WebViewActivity.startActivity(mContext, WebApis.serverHead + appbtnListList.get(3).getH5Url());
                }
                break;
            case "5":
                if (appbtnListList.get(4).getJump().equals("client")) {
                    GoInto(appbtnListList.get(4).getValue());
                } else {
                    WebViewActivity.startActivity(mContext, WebApis.serverHead + appbtnListList.get(4).getH5Url());
                }
                break;
            case "6":
                if (appbtnListList.get(5).getJump().equals("client")) {
                    GoInto(appbtnListList.get(5).getValue());
                } else {
                    WebViewActivity.startActivity(mContext, WebApis.serverHead + appbtnListList.get(5).getH5Url());
                }
                break;
            case "7":
                if (appbtnListList.get(6).getJump().equals("client")) {
                    GoInto(appbtnListList.get(6).getValue());
                } else {
                    WebViewActivity.startActivity(mContext, WebApis.serverHead + appbtnListList.get(6).getH5Url());
                }
                break;
            case "8":
                if (appbtnListList.get(7).getJump().equals("client")) {
                    GoInto(appbtnListList.get(7).getValue());
                } else {
                    WebViewActivity.startActivity(mContext, WebApis.serverHead + appbtnListList.get(7).getH5Url());
                }
                break;
            case "9":
                if (appbtnListList.get(8).getJump().equals("client")) {
                    GoInto(appbtnListList.get(8).getValue());
                } else {
                    WebViewActivity.startActivity(mContext, WebApis.serverHead + appbtnListList.get(8).getH5Url());
                }
                break;
            case "10":
                if (appbtnListList.get(9).getJump().equals("client")) {
                    GoInto(appbtnListList.get(9).getValue());
                } else {
                    WebViewActivity.startActivity(mContext, WebApis.serverHead + appbtnListList.get(9).getH5Url());
                }
                break;
        }
    }

    private void GoInto(String value) {
        switch (value) {
            case "1":
                startActivity(AccountNewActivity.class);
                break;
            case "2":
                startActivity(TeamActivity.class);
                break;
            case "3":
                startActivity(ShopNewActivity.class);
                break;
            case "4":
                startActivity(MachineNewActivity.class);
                break;
            case "5":
                startActivity(AllowActivity.class);
                break;

        }
    }

    @Override
    public void onResume() {
        super.onResume();
        initBottomBanner();
    }
}
